package com.banciyuan.bcywebview.biz.setting;

import android.app.Dialog;
import android.content.Context;
import android.database.DataSetObserver;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.UserApi;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.base.view.wheel.OnWheelChangedListener;
import com.banciyuan.bcywebview.base.view.wheel.WheelView;
import com.banciyuan.bcywebview.base.view.wheel.WheelViewAdapter;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import com.banciyuan.bcywebview.utils.http.BcyPair;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.daoexample.model.Province;

/**
 * Created by hy on 2015/5/4.
 */
public class SelectCityDialog extends Dialog {


    public SelectCityDialog(Context context) {
        super(context);
    }

    public SelectCityDialog(Context context, int theme) {
        super(context, theme);
    }

    protected SelectCityDialog(Context context, boolean cancelable, OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
    }

    public static class Builder {
        protected Context context;
        protected WheelView lvProvince;
        protected WheelView lvCity;
        protected File file;
        protected List<Province> list = new ArrayList<>();
        protected String provinceNum = "1";
        protected String cityNum = "2";
        protected RequestQueue mQueue;
        protected ChangeCityListener changeCityListener;
        protected String newCityName = "";

        protected SelectCityDialog mydialog;

        public Builder(Context context) {
            this.context = context;
            mQueue = VolleyQueue.getRquest(context);
            getCityList(context);
        }

        private void getCityList(Context context) {
            InputStream is = null;
            InputStreamReader inputStreamReader = null;
            try {
                is = context.getResources().getAssets().open("location.json");
                inputStreamReader = new InputStreamReader(is, Charset.defaultCharset());
                Gson gson = new Gson();
                list = gson.fromJson(inputStreamReader, new TypeToken<List<Province>>() {
                }.getType());
                popIllegalData();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    inputStreamReader.close();
                    is.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        protected void popIllegalData() {
            // empty
        }

        public ChangeCityListener getChangeCityListener() {
            return changeCityListener;
        }

        public void setChangeCityListener(ChangeCityListener changeCityListener) {
            this.changeCityListener = changeCityListener;
        }

        public SelectCityDialog create() {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            mydialog = new SelectCityDialog(context, R.style.PcHeadDialog);
            View layout = inflater.inflate(R.layout.select_city_dialog, null);
            init(layout);
            layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mydialog.dismiss();
                }
            });
            mydialog.setContentView(layout);
            return mydialog;
        }

        private void init(View layout) {
            lvProvince = (WheelView) layout.findViewById(R.id.lv_province);
            lvCity = (WheelView) layout.findViewById(R.id.lv_city);
            layout.findViewById(R.id.tv_cancle).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mydialog.dismiss();
                }
            });
            layout.findViewById(R.id.tv_confirm).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    int provinceItem = lvProvince.getCurrentItem();
                    int cityItem = lvCity.getCurrentItem();
                    provinceNum = list.get(provinceItem).getCode();
                    cityNum = list.get(provinceItem).getChildren().get(cityItem).getCode();

                    newCityName = list.get(provinceItem).getName() + " " + list.get(provinceItem).getChildren().get(cityItem).getName();
                    changeCity();
                }
            });

            if (list != null) {
                initProvince2();
                initCity(0);
            }
        }

        protected void changeCity() {
            List<BcyPair> paramsList = new ArrayList<BcyPair>();
            if (UserDataHelper.ifLogin(context))
                paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(context).getToken()));
            paramsList.add(new BcyPair(HttpUtils.PROVINCE, provinceNum));
            paramsList.add(new BcyPair(HttpUtils.CITY, cityNum));
            final HashMap<String, String> params = HttpUtils.getData(paramsList);
            String url = HttpUtils.BASE_URL + UserApi.getModifyaddr();
            Response.Listener<String> onSucc = new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {
                    JSONObject result = null;
                    try {
                        result = new JSONObject(s);
                        String st = result.getString(HttpUtils.UPLOAD_STATUS);
                        String data = result.getString(HttpUtils.UPLOAD_DATA);
                        if (st.equals("1")) {
                            if (null != changeCityListener) {
                                changeCityListener.onCityChanged(newCityName, provinceNum, cityNum);
                            }
                        }
                        mydialog.dismiss();
                        MyToast.show(context, data);
                    } catch (JSONException e) {
                        e.printStackTrace();
                        MyToast.show(context, context.getString(R.string.modify_fail));
                        mydialog.dismiss();
                    }
                }
            };

            Response.ErrorListener onError = new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    mydialog.dismiss();
                }
            };
            StringRequestParam stringRequest = new StringRequestParam(Request.Method.POST, url, params, onSucc, onError);
            mQueue.add(stringRequest);
        }

        private void initCity(final int position) {

            lvCity.setViewAdapter(new CityViewAdapter(position));
            lvCity.setCurrentItem(0);
        }


        private void initProvince2() {

            lvProvince.setBottom(20);
            lvProvince.setTop(20);
            lvProvince.setViewAdapter(new ProviceViewAdapter());
            lvProvince.addChangingListener(new OnWheelChangedListener() {
                @Override
                public void onChanged(WheelView wheel, int oldValue, int newValue) {
                    initCity(newValue);
                }
            });
        }

        class CityViewAdapter implements WheelViewAdapter {
            private final int currPos;

            public CityViewAdapter(int currPos) {
                this.currPos = currPos;
            }

            @Override
            public int getItemsCount() {
                if (!list.isEmpty()) {
                    return list.get(currPos).getChildren().size();
                } else {
                    return 0;
                }
            }

            @Override
            public View getItem(int index, View convertView, ViewGroup parent) {
                TextView tv = (TextView) LayoutInflater.from(context).inflate(R.layout.selected_city_view, parent, false);
                tv.setText(list.get(currPos).getChildren().get(index).getName());
                return tv;
            }

            @Override
            public View getEmptyItem(View convertView, ViewGroup parent) {
                TextView tv = (TextView) LayoutInflater.from(context).inflate(R.layout.selected_city_view, parent, false);
                return tv;
            }

            @Override
            public void registerDataSetObserver(DataSetObserver observer) {

            }

            @Override
            public void unregisterDataSetObserver(DataSetObserver observer) {

            }
        }

        class ProviceViewAdapter implements WheelViewAdapter {
            @Override
            public int getItemsCount() {
                return list.size();
            }

            @Override
            public View getItem(int index, View convertView, ViewGroup parent) {
                TextView tv = (TextView) LayoutInflater.from(context).inflate(R.layout.selected_city_view, parent, false);
                tv.setText(list.get(index).getName());
                return tv;
            }

            @Override
            public View getEmptyItem(View convertView, ViewGroup parent) {
                TextView tv = (TextView) LayoutInflater.from(context).inflate(R.layout.selected_city_view, parent, false);
                return tv;
            }

            @Override
            public void registerDataSetObserver(DataSetObserver observer) {

            }

            @Override
            public void unregisterDataSetObserver(DataSetObserver observer) {

            }
        }

        public interface ChangeCityListener {
            void onCityChanged(String newCity, String provicecode, String citycode);
        }

    }

}
